package edu.ncsu.csc.ip.client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

import edu.ncsu.csc.ip.client.protocol.ProtocolRFCServerImpl;
import edu.ncsu.csc.ip.common.Log;
import edu.ncsu.csc.ip.common.NetworkUtils;
import edu.ncsu.csc.ip.common.Protocol;

//import edu.ncsu.csc.ip.common.Protocol;

/**
 * Handles the downloading of the RFC Index or RFC document
 * for a remote peer; Once the downloading is complete, this thread terminates.
 * 
 * 
 * @author Moin Ayazifar <mayazif@ncsu.edu>
 * @author Steven Elliott <sdelliot@ncsu.edu>
 * 
 */

public class RFCServerThread extends Thread {
	private Socket socket = null;
	private Protocol protocol = null;
	private RFCIndex rfcIndex;
	private ClientInfo clientInfo;

	public RFCServerThread(Socket socket, RFCIndex rfcIndex,
			ClientInfo clientInfo) {
		super("RFCServerThread");
		this.socket = socket;
		this.rfcIndex = rfcIndex;
		this.clientInfo = clientInfo;
		this.protocol = new ProtocolRFCServerImpl(socket, rfcIndex, clientInfo);

	}

	public void run() {
		try {
			PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
			BufferedReader in = new BufferedReader(new InputStreamReader(
					socket.getInputStream()));
			//Log.println(clientInfo +"RFC Server Accepted connection from: [" + NetworkUtils.getRemoteAdress(socket).getHostAddress()+"]");
			String inputLine, outputLine;
			String header = in.readLine();
			if (header != null) {
				inputLine = header + "\n" + in.readLine();
				//Log.printMessage("Message From Client ", inputLine);
				outputLine = protocol.parseMessage(inputLine);
				//Log.printMessage("Message To Client ", outputLine);
				out.print(outputLine);
			}
			out.close();
			in.close();
			socket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
